﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Data.Model;
using NHibernate;
using Senparc.Weixin.MP.Entities;
using NHibernate.Criterion;
using System.Collections.Generic;
using ZLCMS.Business.Util;
using Senparc.Weixin.MP.Helpers;
using DotNet.Common.NHibernateUtil;

namespace ZLCMS.Web.SystemManage.Weixin
{
    public partial class EditMemberCard : System.Web.UI.Page
    {
        protected FrameHelper _frameHelper;

        protected WxMemberCardConfig _cardDb=null;
        protected WxMaterial _materialDb;
        
        protected string _userAccount;

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            _frameHelper = new FrameHelper(this);

            //初始化全局变量值
            InitializeGlobalValue();
            //初始化控件值
            InitializeContent();

            if (IsPostBack)
            {
                Save();
            }
        }

        #region 保存操作 新建/更新 + private void Save()
        /// <summary>
        /// 保存操作 新建/更新
        /// </summary>
        private void Save()
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                ITransaction tran = session.BeginTransaction();

                try
                {
                    if (_cardDb == null)//新建
                    {
                        _materialDb = new WxMaterial();

                        _materialDb.Title = tb_name.Text;
                        _materialDb.MsgType = "mcard";
                        _materialDb.CreateDate = DateTime.Now;
                        _materialDb.UpdateDate = DateTime.Now;
                        _materialDb.Status = "1";
                        _materialDb.OwnerAccount = _userAccount;

                        session.Save(_materialDb);

                        _cardDb = new WxMemberCardConfig();

                        _cardDb.Title = tb_name.Text;
                        _cardDb.Description = tb_desc.Text;
                        _cardDb.Content = tb_content.Text;
                        _cardDb.CardHeadChar = tb_head.Text;
                        _cardDb.CardUrl = fc_card.Value;
                        _cardDb.BackgroupUrl = fc_pic.Value;
                        _cardDb.NeedConfig = cbx_needconfig.Checked ? 1 : 0;
                        _cardDb.CoverUrl = fc_cover.Value;
                        _cardDb.Kind = "0";
                        _cardDb.OwnerAccount = _userAccount;

                        _cardDb.MaterialId = _materialDb.Id;

                        session.Save(_cardDb);
                    }
                    else//修改
                    {
                        _materialDb.UpdateDate = DateTime.Now;

                        session.Update(_materialDb);

                        _cardDb.Title = tb_name.Text;
                        _cardDb.Description = tb_desc.Text;
                        _cardDb.Content = tb_content.Text;
                        _cardDb.CardUrl = fc_card.Value;
                        _cardDb.BackgroupUrl = fc_pic.Value;
                        _cardDb.NeedConfig = cbx_needconfig.Checked ? 1 : 0;
                        _cardDb.CoverUrl = fc_cover.Value;

                        session.Update(_cardDb);
                    }


                    WxMaterial mat = session.Get<WxMaterial>(_cardDb.MaterialId);
                    if (mat == null)
                    {
                        mat = new WxMaterial();
                        mat.CreateDate = DateTime.Now;
                    }
                    mat.MsgType = "mcard";
                    mat.OwnerAccount = _userAccount;
                    mat.Status = "1";
                    mat.Title = _cardDb.Title;
                    mat.UpdateDate = DateTime.Now;
                    session.SaveOrUpdate(mat);


                    WxMaterialNews news = session.CreateQuery("from WxMaterialNews where MaterialId=:mid").SetParameter("mid", mat.Id)
                        .UniqueResult<WxMaterialNews>();
                    if (news == null)
                    {
                        news = new WxMaterialNews();
                    }
                    news.Content = _cardDb.Content;
                    news.ContentType = "URL";
                    news.Description = _cardDb.Description;
                    news.MaterialId = mat.Id;
                    news.OwnerAccount = _userAccount;
                    news.Title = _cardDb.Title;
                    session.SaveOrUpdate(news);

                    _cardDb.MaterialId = mat.Id;
                    session.SaveOrUpdate(_cardDb);


                    session.Flush();
                    tran.Commit();
                }
                catch (System.Exception ex)
                {
                    tran.Rollback();

                    _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }

            _frameHelper.Alert(new ReturnCode()
            {
                statusCode = 200,
                message = "操作成功!",
                navTabId = _frameHelper.NavTabId
            });
        } 
        #endregion

        #region 初始化全局变量 + protected void InitializeGlobalValue()
        /// <summary>
        /// 初始化全局变量
        /// </summary>
        protected void InitializeGlobalValue()
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                try
                {
                    _cardDb = session.CreateCriteria<WxMemberCardConfig>().Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxMemberCardConfig>();

                    if (_cardDb != null)
                    {
                        _materialDb = session.CreateCriteria<WxMaterial>().Add(Expression.Eq("Id", _cardDb.MaterialId)).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxMaterial>();
                    }
                }
                catch (System.Exception ex)
                {
                    _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }
        } 
        #endregion

        #region 初始化页面内容 + protected void InitializeContent()
        /// <summary>
        /// 初始化页面内容
        /// </summary>
        protected void InitializeContent()
        {
            //页面控件值
            if (!IsPostBack)
            {
                if (_cardDb != null)
                {
                    tb_name.Text = _cardDb.Title;
                    tb_desc.Text = _cardDb.Description;
                    tb_content.Text = _cardDb.Content;
                    fc_card.Value = _cardDb.CardUrl;
                    fc_pic.Value = _cardDb.BackgroupUrl;
                    fc_cover.Value = _cardDb.CoverUrl;
                    tb_head.Text = _cardDb.CardHeadChar;
                    tb_head.Attributes.Add("readonly", "true");
                    cbx_needconfig.Checked = _cardDb.NeedConfig == 1 ? true : false;
                }
            }
        } 
        #endregion
    }
}
